package com.maserb.monitor.wechat;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class WeChatSign {
	
	private static final String TAG = WeChatSign.class.getName();
	/**随机字符串*/
	public final String ECHOSTR = "echostr";
	/**微信加密签名  */
	public final String SIGNATURE = "signature";
	/**时间戮 */
	public final String TIMESTAMP = "timestamp";
	/**随机数*/
	public final String NONCE = "nonce";

	@Autowired
    WeChatPayConfig weChatPayConfig;

	@Autowired
    WeChatAccessToken weChatAccessToken;
	
	 /** 
     * 验证签名 
     * @param signature 
     * @param timestamp 
     * @param nonce 
     * @return 
     */  
    public boolean checkSignature(String signature, String timestamp, String nonce){
    	// 将 token, timestamp, nonce 三个参数进行字典排序  
        String[] arr = new String[]{weChatPayConfig.TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();  
        for(int i = 0; i < arr.length; i++){  
            content.append(arr[i]);  
        }  
        MessageDigest md = null;  
        String tmpStr = null;  
          
        try {  
            md = MessageDigest.getInstance("SHA-1");  
            // 将三个参数字符串拼接成一个字符串进行 shal 加密  
            byte[] digest = md.digest(content.toString().getBytes());  
            tmpStr = MD5Util.byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        content = null;  
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信  
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()): false;  
    }  

    private String createNonceStr() {
        return UUID.randomUUID().toString();
    }

    public String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = createNonceStr();
        String timestamp = createTimestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        log.info(TAG,string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = MD5Util.byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }

        //设置URL(配置文件中的域名)
        url = weChatPayConfig.REDIRECT_URI_HOME + url;
        
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appid", weChatPayConfig.APPID);

        return ret;
    }

    public Map<String, String> sign(String url){
    	if(weChatAccessToken.getJsTicket() == null || weChatAccessToken.getJsTicket().isEmpty()){
    		log.info(TAG, "sign failed cause JsTicket is null!--------");
			return null;
    	}else{
    		return sign(weChatAccessToken.getJsTicket(), url);
    	}
    }
}
